import axios from 'axios';
import baseUrl from './apiRoot.js';
import { Notification } from 'element-ui';
import store from '../store/index';
import { getToken } from '@/utils/auth';

// 实例化
const myAxios = axios.create({
  baseURL: baseUrl,
  timeout: 600000
});

// 添加请求拦截器
myAxios.interceptors.request.use(config => {
  config.headers['access-token'] = config.headers['access-token'] ? config.headers['access-token'] : getToken();
  return config;
}, error);

// 添加响应拦截器
myAxios.interceptors.response.use(response => {
  let success = true,
    resultMsg = '',
    data = '';
  if (response && (response.status == 200 || response.status == 201)) {
    if (response.data && response.data.code == 0) {
      data = response.data.data || '';
      resultMsg = response.data.msg || '';
    } else if (response.data && response.data.code == 401) {
      resultMsg = `${response.data.msg}`;
      success = false;
      Notification({
        message: resultMsg || '服务器开小差中，请稍后再试！',
        type: 'error'
      });
      store.dispatch('Logout');
    } else {
      resultMsg = `${response.data.msg}`;
      success = false;
      Notification({
        message: resultMsg || '服务器开小差中，请稍后再试！',
        type: 'error'
      });
    }
  } else if (response && response.status) {
    resultMsg = `${response.data.msg}`;
    success = false;
    Notification({
      message: resultMsg || '服务器开小差中，请稍后再试！',
      type: 'error'
    });
  }
  return {
    resultMsg,
    success,
    data
  };
}, error);

function error(error) {
  let resultMsg = `网络异常：`;
  if (error.response) {
    resultMsg = `${resultMsg} ${error.response.status} ${error.response.statusText}`;
  }
  return {
    resultMsg: resultMsg,
    success: false
  };
}

export default myAxios;
